#include "UFLTimer.h"
#include <time.h>
#include <iostream>

using namespace ufl;

UFLTimer::UFLTimer()
:_secondsPerCount(0.0f), _deltaTime(-1.0f), _baseTime(0),
_pausedTime(0), _stopTime(0), _prevTime(0), _currTime(0), _stopped(false)
{
	_secondsPerCount = static_cast<double> (1) / CLOCKS_PER_SEC;
}

float UFLTimer::totalTime() const
{
	if ( _stopped )
	{
		return static_cast<float>( ((_stopTime - _pausedTime) - _baseTime) * _secondsPerCount );
	}
	else
	{
		return static_cast<float>( ((_currTime - _pausedTime) - _baseTime) * _secondsPerCount );
	}
}

float UFLTimer::deltaTime() const
{
	return static_cast<float>(_deltaTime);
}

void UFLTimer::reset()
{
	ufl_int64 currTime = clock();

	_baseTime = currTime;
	_prevTime = currTime;
	_stopTime = 0;
	_stopped  = false;
}

void UFLTimer::start()
{
	ufl_int64 startTime = clock();

	if ( _stopped )
	{
		_pausedTime += (startTime - _stopTime);

		_prevTime = startTime;
		_stopTime = 0;
		_stopped = false;
	}
	_baseTime = clock();
}

void UFLTimer::stop()
{
	if ( !_stopped )
	{
		ufl_int64 currTime = clock();

		_stopTime = currTime;
		_stopped = true;
	}
}

void UFLTimer::tick()
{
	if ( _stopped )
	{
		_deltaTime = 0.0;
		return;
	}

	ufl_int64 currTime = clock();
	_currTime = currTime;

	// 计算当前帧和前一帧的时间差
	_deltaTime = static_cast<double>( (_currTime - _prevTime) * _secondsPerCount );
    
	// 为下一帧准备
	_prevTime = _currTime;
    
	// 强制转为正值。
	// 原因在于如果处理器进入了省电模式或人为打断处理器时，_deltaTime有可能为负值
	if (_deltaTime < 0.0)
	{
		_deltaTime = 0.0;
	}
}